package application

import (
	"context"
	"gitee.com/alex_li/rodinbell/etc"
	"gitee.com/alex_li/rodinbell/reader"
	"github.com/lishimeng/go-log"
	"time"
)

var container map[string]*reader.Reader

func init() {
	container = make(map[string]*reader.Reader)
}

func startReader(ctx context.Context){

	// 清理不可用的设备-------------------------
	var marker []string
	for name, w := range container {
		if !w.State {
			marker = append(marker, name)
		}
	}
	for _, name := range marker {
		log.Info("remove reader: %s", name)
		delete(container, name)
	}
	// --------------------------------------

	list, err := etc.SerialPorts()
	for _, uart := range list {
		var w *reader.Reader
		if _, ok := container[uart.Name]; ok { // 已经在设备列表中
			continue
		}

		if !etc.IsReader(uart) { // 不是读卡器的端口
			continue
		}

		log.Info("init reader: %s", uart.Name)
		w, err = createReader(ctx, uart.Name, etc.Config.Connector.Port)
		if err != nil {
			return
		}
		container[uart.Name] = w
		go work(w)
	}

	return
}

func createReader(ctx context.Context, name string, baud uint) (r *reader.Reader, err error) {
	opts := reader.Options{
		BaudRate: baud,
		PortName: name,
		Antennas: etc.Config.Antenna.Antennas,
	}
	session := reader.Open(ctx, &opts)
	r = &session
	return
}

func work(r *reader.Reader) {
	defer func() {
		if err := recover(); err != nil {
			log.Info(err)
			r.State = false
		}
	}()
	for {
		select {
		case <-r.Ctx.Done():
			break
		default:
			inventory(*r)
			time.Sleep(time.Millisecond * 100)
		}
	}
}

func inventory(session reader.Reader) {
	session.Inventory(onData)
	//session.FastInventory(onData)
}
